package maple.thelittleredbook.logging.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import maple.thelittleredbook.logging.dto.SysLogHistoryResponse;
import maple.thelittleredbook.logging.entity.SysLog;
import maple.thelittleredbook.logging.mapper.SysLogMapper;

/**
 * 管理员系统日志服务
 */
@Slf4j
@Service
public class AdminSysLogService {

    private final SysLogMapper sysLogMapper;

    @Autowired
    public AdminSysLogService(SysLogMapper sysLogMapper) {
        this.sysLogMapper = sysLogMapper;
    }

    /**
     * 获取系统日志历史列表
     *
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @param userId 用户ID筛选
     * @param requestMethod 请求方法筛选
     * @param operation 操作类型筛选（模糊匹配）
     * @param errorOnly 是否只查询错误请求
     * @return 系统日志历史
     */
    public SysLogHistoryResponse getSysLogHistory(Integer pageNum, Integer pageSize,
                                                  Long userId, String requestMethod,
                                                  String operation, Boolean errorOnly) {
        // 1. 参数验证和默认值设置
        pageNum = pageNum != null && pageNum > 0 ? pageNum : 1;
        pageSize = pageSize != null && pageSize > 0 && pageSize <= 100 ? pageSize : 20;
        requestMethod = requestMethod != null && !requestMethod.trim().isEmpty() ? requestMethod : "all";
        operation = operation != null && !operation.trim().isEmpty() ? operation : "all";
        errorOnly = errorOnly != null ? errorOnly : false;

        log.info("查询系统日志历史，页码: {}, 每页数量: {}, 用户ID: {}, 请求方法: {}, 操作类型: {}, 仅错误: {}",
                pageNum, pageSize, userId, requestMethod, operation, errorOnly);

        // 2. 创建分页对象
        Page<SysLog> page = new Page<>(pageNum, pageSize);

        // 3. 处理筛选参数
        String finalRequestMethod = "all".equals(requestMethod) ? null : requestMethod;
        String finalOperation = "all".equals(operation) ? null : operation;

        // 4. 查询数据库
        IPage<SysLog> result = sysLogMapper.selectPageWithFilters(
                page, userId, finalRequestMethod, finalOperation, errorOnly);

        // 5. 构建响应对象
        SysLogHistoryResponse response = new SysLogHistoryResponse();
        response.setTotal(result.getTotal());
        response.setTotalPages((int) Math.ceil((double) result.getTotal() / pageSize));
        response.setPageNum(pageNum);
        response.setPageSize(pageSize);
        response.setLogs(result.getRecords());

        log.info("系统日志查询完成，总记录数: {}, 当前页记录数: {}", result.getTotal(), result.getRecords().size());

        return response;
    }

    /**
     * 根据ID获取系统日志详情
     *
     * @param logId 日志ID
     * @return 系统日志详情
     */
    public SysLog getSysLogById(Long logId) {
        if (logId == null) {
            throw new IllegalArgumentException("日志ID不能为空");
        }

        SysLog sysLog = sysLogMapper.selectById(logId);
        if (sysLog == null) {
            throw new IllegalArgumentException("日志记录不存在");
        }

        return sysLog;
    }
}